package com.zoe.app.config;

import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.jwt.JWTUtil;
import com.zoe.app.exception.IdempotentException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * @author Zoe.Zhang
 * @date 2021/10/24
 * @description
 */
@Component
public class TokenService {
    private byte[] signature = StrUtil.bytes("zoeyyds1234");
    @Autowired
    private RedisService redisService;
    Map<String, Object> map = new HashMap<String, Object>() {
        private static final long serialVersionUID = 1L;

        {
            put("uid", IdUtil.getWorkerId(1, 1));
            put("expire_time", System.currentTimeMillis() + 1000 * 60 * 60 * 24 * 15);
        }
    };

    public String createToken() {
        String token = JWTUtil.createToken(map, signature);
        redisService.setEx(token, token, 7200L);
        return token;
    }

    public boolean verifyToken(HttpServletRequest request) throws IdempotentException {
        String token = request.getHeader("token");

        // 判断请求头是否存在token
        if (StrUtil.isBlank(token)) {
            throw new IdempotentException("token不存在1");
        }
        boolean exists = redisService.exists(token);

        // 判断redis是否存在改token
        if (!exists) {
            throw new IdempotentException("重复操作!2");
        }

        // 验证token合法性
        boolean verify = JWTUtil.verify(token, signature);
        if (!verify) {
            throw new IdempotentException("违法的token3");
        }

        // 是否刚好被人操作了
        boolean remove = redisService.remove(token);
        if (!remove) {
            throw new IdempotentException("重复操作!4");
        }
        return true;
    }
}
